package com.grandtech.insurance.common.db.mybites.utils;

import com.grandtech.insurance.common.db.jdbc.sql.ReflectUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 游标转实体 Created by zy on 2016/12/23.
 */

public final class ResultSetUtil {

    private ResultSetUtil() {

    }


    /**
     * Map转成实体对象
     *
     * @param resultSet map实体对象包含属性
     * @param clazz     实体对象类型
     * @return
     */
    public static Object resultSet2Single(ResultSet resultSet, Class<?> clazz) {
        if (resultSet == null) return null;
        Object obj = null;
        try {
            obj = clazz.newInstance();
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                try {
                    String fieldName = ReflectUtil.getColumnName(field);
                    Object object = resultSet.getObject(fieldName);
                    field.set(obj, object);
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }


    public static Object resultSet2List(ResultSet resultSet, Class<?> clazz) {
        List<Object> objects = new ArrayList<>();
        try {
            Object o = null;
            while (resultSet.next()) {
                o = resultSet2Single(resultSet, clazz);
                objects.add(o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return objects;
        }
    }
}
